<?php
/*
 * @开发工具: JetBrains PhpStorm.
 * @文件名：User.class.php
 * @类功能: 用户控制器
 * @开发者: 陈旭林
 * @开发时间： 2017-09-01
 * @版本：version 1.0
 */

namespace app\credit\controller;

use app\common\cache\bank\IBankCache;
use app\common\cache\bank\IBankTypeCache;
use app\common\cache\common\IAnnouncementCache;
use app\common\cache\common\IAreaCache;
use app\common\cache\common\IConfigCache;
use app\common\cache\common\ILanguage;
use app\common\cache\common\IProtocolCache;
use app\common\controller\ApiBaseController;
use app\common\controller\CreditBaseController;
use app\common\enum\AppType;
use app\common\enum\IsDelete;
use app\common\enum\IsReal;
use app\common\enum\SuggestType;
use app\common\enum\Source;
use app\common\ext\IConfig;
use app\common\ext\IDb;
use app\common\ext\IPhoto;
use app\common\ext\ISms;
use app\common\ext\IUrl;
use app\common\util\Oss;
use app\common\util\StringUtil;
use think\Cache;
use think\Config;

class System extends CreditBaseController {

    /**
     * @功能：系统初始接口
     * @开发者：cxl
     */
    public function start(){
        //接收参数
        $device  = self::get_data('device_no',self::NOT_EMPTY,"设备编号错误！");
        $os = self::get_data('os',self::NOT_EMPTY,"系统区分错误！");
        $version  = self::get_data('version',self::NOT_EMPTY,"系统版本错误！");

        //检测保存设备ID
        if (empty($device) || strlen($device) != 32) {
            self::set_code(self::ERR_0001);
            self::set_msg("设备编号错误！");
            self::send();
        }

        //判断系统区分是否正确
        if(!in_array($os,array(Source::Android,Source::Ios))){
            self::set_code(self::ERR_0002);
            self::set_msg("系统区分错误！");
            self::send();
        }

        //设置数据
        self::set_token(self::USER,null); //设置用户编号
        self::set_token(self::DEVICE,$device); //设置设备编号
        self::set_token(self::OS,$os); //设置系统区分
        self::set_token(self::VERSION,$version); //设置版本信息

        //返回参数
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value(self::SUBSCRIPT_TOKEN,self::get_token());
        self::set_value("unix",time());
        self::set_value("datetime",get_date_time());
        self::send();
    }

    /**
     * @功能：获取常量接口
     * @开发者：cxl
     */
    public function config(){
        //接收参数
        $config_code  = self::get_data('config_code');

        //判断是否取得全部常量信息
        $config_value = array();
        if(empty($config_code)){
            //取得全部常量信息
            $const_list = IConfigCache::getList();
            if(!empty($const_list) && is_array($const_list)){
                //循环设置数据
                foreach($const_list as $item){
                    $config_value[$item['config_code']] = $item['val'];
                }
            }
        }else{
            //判断是否存在多个
            if(stripos($config_code,",") === false){
                //取得单个常量
                $config_value[$config_code] = IConfig::getValue($config_code);
            }else{
                //取得多个常量
                $config_value_array = explode(",",$config_code);

                //取得常量内容、、、、
                foreach($config_value_array as $value){
                    $config_value[$value] = IConfig::getValue($value);
                }
            }
        }

        //取得常量值
        if (empty($config_value)) {
            self::set_code(self::ERR_0001);
            self::set_msg("取得常量失败！");
            self::send();
        }

        //成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("config",$config_value);
        self::send();
    }

    /**
     * @功能：发生短息验证码
     * @开发者：cxl
     */
    public function sms(){
        //接收参数
        $phone  = self::get_data('phone',self::PHONE,"请输入正确的手机号！");

        //判断验证码发送次数
        $sms_count = ISms::getCount(AppType::XD,$phone);
        if($sms_count === false){
            self::set_code(self::WARNING_0001);
            self::set_msg("发送短信超过限制次数！");
            self::send();
        }

        //发送短信
        $verification = rand(100000, 999999);
        $sms = ISms::Verification(AppType::XD,$phone,$verification);
        if($sms === false){
            self::set_code(self::WARNING_0002);
            self::set_msg("发送短信失败！");
            self::send();
        }

        //返回成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("verification",$verification);
        self::send();
    }

    /**
     * @功能：取得广告位图片
     * @开发者：cxl
     */
    public function ad(){
        //取得广告位图片
        $location_code  = self::get_data('location_code',self::NOT_EMPTY,"广告位编码不能为空！");

        //判断广告位是否存在
        $ad_location_where['ad_location_code'] = $location_code;
        $ad_location_where['app_type'] = AppType::XD;
        $ad_location_info = IDb::getInstance('com_ad_location')->setDbWhere($ad_location_where)->row();
        if(empty($ad_location_info['ad_location_id'])){
            self::set_code(self::ERR_0001);
            self::set_msg("取得广告位失败！");
            self::send();
        }

        //判断取得广告位张数
        $ad_number = intval($ad_location_info['number']);
        if($ad_number <= 0){
            $ad_number = 1;
        }

        //取得广告列表
        $ad_where['is_delete'] = IsDelete::No;
        $ad_where['ad_location_id'] = $ad_location_info['ad_location_id'];
        $ad_list = IDb::getInstance('com_ad')
            ->setDbFiled("ad_id,ad_name,ad_photo_url,ad_goto_url")
            ->setDbWhere($ad_where)
            ->setDbOrder("city_id desc,order_by")
            ->setDbLimit($ad_number)
            ->sel();

        //判断时间是否正确
        if(empty($ad_list)){
            $ad_list = array();
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("ad_list",$ad_list);
        self::send();
    }

    /**
     * @功能：协议借款
     * @开发者：cxl
     */
    public function protocol() {
        //接收参数
        $protocol_code = self::get_data('protocol_code', self::NOT_EMPTY, '协议编号不能为空');

        //判断是否正确
        $protocol_info = IProtocolCache::getInfo($protocol_code);
        if(empty($protocol_info['protocol_id'])){
            self::set_code(self::WARNING_0001);
            self::set_msg("取得协议内容失败！");
            self::send();
        }

        //取得地址
        $url = IUrl::getProtocol($protocol_code);

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("url",$url);
        self::send();
    }

    /**
     * @功能：取得行政区域
     * @开发者：cxl
     */
    public function area(){
        //接收参数
        $parent_id  = self::get_data('parent_id');

        //判断上层节点是否存在
        if(empty($parent_id)){
            $parent_id = 0;
        }

        //取得区域列表
        $area_list = IAreaCache::getList($parent_id);
        if($area_list === false){
            self::set_code(self::WARNING_0001);
            self::set_msg("取得区域信息失败！");
            self::send();
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("area_list",$area_list);
        self::send();
    }

    /**
     * @功能：取得行政区域定位
     * @开发者：cxl
     */
    public function location(){
        //取得区域列表
        $area_list = IAreaCache::getLocation();
        if(empty($area_list)){
            self::set_code(self::SUCCESS);
            self::set_msg("成功！");
            self::set_value("area_list",array());
            self::send();
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("area_list",$area_list);
        self::send();
    }

    /**
     * @功能：取得定位城市编号
     * @开发者：cxl
     */
    public function city(){
        //接收城市
        $city_name  = self::get_data('city_name');

        //整理数据
        $city_name = str_ireplace(array("自治县","自治州","自治区","市","地区","州","区"),"",$city_name);

        //判断定位是否失败
        $com_area_where['area_type'] = 2;
        $com_area_where['area_name'] = array("like","%{$city_name}%");
        $com_area_where['is_delete'] = IsDelete::No;
        $area_info = IDb::getInstance('com_area')
            ->setDbFiled("area_id,acronym,parent_id")
            ->setDbWhere($com_area_where)
            ->row();

        //判断信息是否正确
        if(empty($area_info)){
            //实例化对象
            $area_id = IConfig::getValue("DefaultLocation");
            $area_info = IAreaCache::getInfo($area_id);
            if(empty($area_info)){
                self::set_code(self::WARNING_0001);
                self::set_msg("取得定位信息失败！");
                self::send();
            }
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_values($area_info);
        self::send();
    }

    /**
     * @功能：系统公告列表
     * @开发者：cxl
     */
    public function announcement_list(){
        //接收参数
        $user_id = self::$uid;
        $did = self::$did;
        $bottom_id  = self::get_data('bottom_id');

        //判断是否阅读
        $announcement_list = IAnnouncementCache::getList(AppType::XD,$bottom_id);

        //判断公告是否存在
        if (!empty($announcement_list) && is_array($announcement_list)) {
            //循环判断是否读取
            foreach ($announcement_list as &$data) {
                //判断是否阅读
                $announcement_user_count = IDb::getInstance('com_announcement_user')
                    ->setDbWhere("announcement_id='{$data['announcement_id']}' and (user_id='{$user_id}' or did='{$did}')")
                    ->con();
                if ($announcement_user_count > 0) {
                    $data['is_read'] = IsReal::yes;
                } else {
                    $data['is_read'] = IsReal::not;
                }
            }
        }

        //返回结果
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("announcement_list",$announcement_list);
        self::send();
    }

    /**
     * @功能：设置阅读状态
     * @开发者：cxl
     */
    public function announcement_read(){
        //接收参数
        $user_id = self::$uid;
        $did = self::$did;
        $announcement_id  = self::get_data('announcement_id',self::NOT_EMPTY,"公告编号不能为空！");

        //判断记录是否已经存在
        $announcement_user_count = IDb::getInstance('com_announcement_user')->setDbWhere("announcement_id='{$announcement_id}' and (user_id='{$user_id}' or did='{$did}')")->con();
        if($announcement_user_count <= 0) {
            //添加阅读信息
            $announcement_user_data['announcement_id'] = $announcement_id;
//            if(!empty($user_id)) $announcement_user_data['user_id'] = $user_id;
            $announcement_user_data['did'] = $did;
            $announcement_user_data['create_time'] = get_date_time();
            $announcement_user_add = IDb::getInstance('com_announcement_user')->setDbData($announcement_user_data)->add();
            if($announcement_user_add === false){
                self::set_code(self::WARNING_0001);
                self::set_msg("设置阅读状态失败！");
                self::set_values($announcement_user_data);
                self::send();
            }
        }

        //返回结果
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::send();
    }

    /**
     * @功能：系统消息
     * @开发者：cxl
     */
    public function message(){
        //接收参数
        $user_id = self::$uid;
        $bottom_id  = self::get_data('bottom_id');

        //设置查询条件
        $message_where['agent_admin_id'] = $user_id;
        if(!empty($bottom_id)) $message_where['message_id'] = array("lt",$bottom_id);

        //修改用户实名信息
        $message_list = IDb::getInstance("com_message")->setDbWhere($message_where)->setDbOrder("message_id desc")->setDbLimit(10)->sel();
        if($message_list === false){
            self::set_code(self::WARNING_0001);
            self::set_msg("取得系统消息失败！");
            self::send();
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("message_list",$message_list);
        self::send();
    }

    /**
     * @功能：系统消息读取
     * @开发者：cxl
     */
    public function message_read(){
        //接收参数
        $user_id = self::$uid;
        $message_id  = self::get_data('message_id',self::NUMBER,"消息编号不能为空！");

        //修改用户实名信息
        $message_where['agent_admin_id'] = $user_id;
        $message_where['message_id'] = $message_id;
        $message_data['is_read'] = 2;
        $message_upd = IDb::getInstance("com_message")->setDbWhere($message_where)->setDbData($message_data)->upd();
        if($message_upd === false){
            self::set_code(self::WARNING_0001);
            self::set_msg("设置消息读取状态失败！");
            self::send();
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::send();
    }

    /**
     * @功能：取得未读取数量（公告、消息）
     * @开发者：cxl
     */
    public function not_read_num(){
        //接收参数
        $user_id = self::$uid;
        $did = self::$did;

        //取得未读取公告数量,设置条件
        $app_type = AppType::XD;
        $is_delete = IsDelete::No;
        $announcement_where = "ca.app_type='{$app_type}' and ca.is_delete='{$is_delete}' and not exists (select 1 from xx_com_announcement_user as cau where ca.announcement_id=cau.announcement_id and (cau.user_id='{$user_id}' or cau.did='{$did}'))";
        $announcement_count = IDb::getInstance("com_announcement as ca")->setDbWhere($announcement_where)->con();
        if($announcement_count === false){
            $announcement_count = 0;
        }

        //判断用户是否登录
        if(!empty($user_id)) {
            //取得未读取消息
            $message_where['user_id'] = $user_id;
            $message_where['is_read'] = 1;
            $message_count = IDb::getInstance("com_message")->setDbWhere($message_where)->con();
            if ($message_count === false) {
                $message_count = 0;
            }
        }else{
            $message_count = 0;
        }

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("announcement_not_read_count",$announcement_count);
        self::set_value("message_not_read_count",$message_count);
        self::send();
    }

    /**
     * @功能：已经反馈列表
     * @开发者：cxl
     */
    public function suggest_list(){
        //接收参数
        $agent_admin_id = self::$uid;

        //添加意见反馈
        $suggest_where['agent_admin_id'] = $agent_admin_id;
        if(!empty($bottom_id)) $suggest_where['suggest_id'] = array("lt",$bottom_id);
        $suggest_list = IDb::getInstance("com_suggest")->setDbWhere($suggest_where)->setDbOrder("create_time desc")->sel();
        if($suggest_list === false){
            self::set_code(self::WARNING_0001);
            self::set_msg("取得建议列表失败！");
            self::send();
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("suggest_list",$suggest_list);
        self::send();
    }

    /**
     * @功能：已经反馈
     * @开发者：cxl
     */
    public function suggest(){
        //接收参数
        $agent_admin_id = self::$uid;
        $content  = self::get_data('content',self::NOT_EMPTY,"意见反馈内容不能为空！");
        $content  = htmlspecialchars($content);

        //添加意见反馈
        $suggest_data['agent_admin_id'] = $agent_admin_id;
        $suggest_data['suggest_type'] = SuggestType::AgentAdmin;
        $suggest_data['content'] = $content;
        $suggest_data['create_time'] = get_date_time();
        $suggest_add = IDb::getInstance("com_suggest")->setDbData($suggest_data)->add();
        if($suggest_add === false){
            self::set_code(self::WARNING_0001);
            self::set_msg("意见反馈失败！");
            self::send();
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::send();
    }

    /**
     * @功能：获取初始token
     * @开发者：gys
     */
    public function get_init_token(){
        //接收参数
        $device  = self::get_data('device_no',self::NOT_EMPTY,"设备编号错误！");
        $os = self::get_data('os',self::NOT_EMPTY,"系统区分错误！");
        $version  = self::get_data('version',self::NOT_EMPTY,"系统版本错误！");

        //检测保存设备ID
        if (empty($device) || strlen($device) != 32) {
            self::set_code(self::ERR_0001);
            self::set_msg("设备编号错误！");
            self::send();
        }

        //判断系统区分是否正确
        if(empty(CALL_SOURCE)){
            self::set_code(self::ERR_0002);
            self::set_msg("系统区分错误！");
            self::send();
        }

        //设置数据
        self::set_token(self::USER,null); //设置用户编号
        self::set_token(self::DEVICE,$device); //设置设备编号
        self::set_token(self::OS,$os); //设置系统区分
        self::set_token(self::VERSION,$version); //设置版本信息

        //返回参数
        return self::get_token();
    }

    /**
     * @功能：取得银行列表
     * @开发者：cxl
     */
    public function bank_list(){
        //取得银行列表
        $city_id  = self::get_data('city_id');

        //实例化对象
        $bank_list = IBankCache::getCreditList($city_id); //TODO 判断城市

        //整理数据
        if(!empty($bank_list) && is_array($bank_list)) {
            //整理数据
            foreach ($bank_list as &$data) {
                //实例化对象
                $bank_info = IBankTypeCache::getInfo($data['bank_type_id']);
                if(empty($bank_info['bank_type_name'])){
                    self::set_code(self::WARNING_0001);
                    self::set_msg("取得银行列名称失败！");
                    self::send();
                }

                //返回值
                $data['bank_type_name'] = $bank_info['bank_type_name'];
            }
        }else{
            $bank_list = array();
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("bank_list",$bank_list);
        self::send();
    }

    /**
     * @功能：取得省市区域
     * @开发者：gys
     */
    public function province_city(){
        $area_list = IAreaCache::getAllList(1);
        foreach ($area_list as &$val){
            $val['child'] = IAreaCache::getList($val['area_id']);
        }

        //返回值
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_value("area_list",$area_list);
        self::send();
    }

    /**
     * @功能：言语包功能
     * @开发者：gys
     */
    public function lang(){
        $lang_list = ILanguage::getList(AppType::XD,self::$verify);

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_values(['lang'=>$lang_list]);
        self::send();
    }









    /**
     * @功能：上传图片
     * @开发者：cxl
     */
    public function upload() {
        //接收参数
        $path = self::get_data('path', self::NOT_EMPTY, '图片存储目录名称不能为空');

        //实例化对象
        $photo = IPhoto::oss($path, "file");

        //判断上传是否成功
        if(strtolower($photo['code']) != "0") {
            self::set_code(self::ERR_0001);
            self::set_msg("上传失败：{$photo['msg']}");
            self::send();
        }

        //生产网络地址
        $photo['web_url'] = $photo['url'];

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_values($photo);
        self::send();
    }

    /**
     * @功能：取得oss上传签名
     * @开发者：gys
     */
    public function upload_oss_sign(){
        $access_id = Config::get("oss.access_key_id");
        $access_key = Config::get("oss.access_key_secret");
        $endpoint = Config::get("oss.endpoint");
        $bucket = Config::get("oss.bucket");
        $url = Config::get("oss.url");

        $oss = new Oss($access_id,$access_key,$endpoint,$bucket);

        $data['upload_url'] = $url;
        $data['access_id'] = $access_id;
        $data['policy'] = $oss->getUploadPolicy();
        $data['signature'] = $oss->getUploadSignature($data['policy']);
        $data['key'] = md5(StringUtil::randString(32).self::$uid);

        //操作成功
        self::set_code(self::SUCCESS);
        self::set_msg("成功！");
        self::set_values($data);
        self::send();
    }
}
